<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="只允许为三级分类设置相关参数" type="warning" :closable="false" show-icon>
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>
            选择商品分类:
          </span>
          <el-cascader v-model="selectCatList" :options="catList"
            :props="{ expandTrigger: 'hover',label:'cat_name',value: 'cat_id'}" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tabs 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数
          </el-button>
          <el-table :data="manyTable" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template scope="{row}">
                <el-tag v-for="(item,index) in row.attr_vals" :key="index" closable @close="handleClose(index,row)">
                  {{item}}</el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <!-- 索引列表 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template scope="{row}">
                <!-- {{row.attr_id}} -->
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(row.attr_id)">编辑
                </el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParmas(row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数 -->
        <el-tab-pane label="静态参数" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性
          </el-button>

          <el-table :data="onlyTable" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template scope="{row}">
                <!-- {{row.inputVisible}} -->
                <el-tag v-for="(item,index) in row.attr_vals" :key="index" closable @close="handleClose(index,row)">
                  {{item}}</el-tag>
                <el-input class=" input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>

              </template>

            </el-table-column>
            <!-- 索引列表 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template scope="{row}">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(row.attr_id)">编辑
                </el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParmas(row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的弹框 -->
    <el-dialog :title="'添加'+ titletext" :visible.sync="addDialogVisible" width="50%" @close="addformClose">
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="100px" :inline="false"
        size="normal">
        <el-form-item :label="titletext" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormFn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的弹框 -->
    <el-dialog :title="'添加'+ titletext" :visible.sync="editDialogVisible" width="50%" @close="editformClose">
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="100px" :inline="false"
        size="normal">
        <el-form-item :label="titletext" prop="attr_name">
          <!-- {{editForm.attr_name}} -->
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data () {
    return {
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      activeName: 'many',
      // 商品分类列表
      catList: [],
      // 级联选择框配置对象
      catProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联双向绑定的数组
      selectCatList: [],
      manyTable: [],
      onlyTable: [],
      addDialogVisible: false,
      // 修改参数的数据
      editForm: {

      },
      // 修改参数弹框的显示隐藏
      editDialogVisible: false,
      // 修改参数的验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 删除tag函数
    async handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      const { meta } = await this.saveAttrVals(row)
      if (meta.status !== 200) return this.$Message.error('添加失败')
      this.$Message.success('删除成功')
    },
    async handleInputConfirm (row) {
      // console.log('ok')
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      row.attr_vals.push(row.inputValue.trim())
      // 如果不设置成空，是聚焦点会触发两次push事件
      row.inputValue = ''
      row.inputVisible = false
      // res 是一个promise对象 必须要用await接受
      const { meta } = await this.saveAttrVals(row)
      // console.log(res)
      if (meta.status !== 200) return this.$Message.error('添加失败')
      this.$Message.success('添加成功')
    },
    // 单独封装的修改tag数据的axios请求
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        // 在获取attr_vals的时候把字符串转化为数组，中间是空格隔开的
        attr_vals: row.attr_vals.join(' ')
      })
      // res 是一个promise对象
      return res
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 删除数据
    async removeParmas (id) {
      // this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   this.$message({
      //     type: 'success',
      //     message: '删除成功!'
      //   })
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消删除'
      //   })
      // })
      const confim = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // comfim接受的是一个字符串，成功就是confirm
      // console.log(confim)
      if (confim !== 'confirm') return this.$Message.info('已取消删除')

      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$Message.error('删除失败')
      this.$Message.success('删除成功')
      this.editDialogVisible = false
      this.getParams()
    },
    // 显示修改弹框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      this.editForm = res.data
      // console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 修改参数弹框的更新函数
    async editFormFn () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$Message.error('修改数据失败')
        this.$Message.success('修改数据成功')
        this.editDialogVisible = false
        this.getParams()
      })
    },
    // 添加数据的方法
    addFormFn () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$Message.error('添加数据失败')
        this.$Message.success('添加数据成功')
        this.addDialogVisible = false
        this.getParams()
      })
    },
    addformClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 修改参数弹框的恢复
    editformClose () {
      // this.$refs.editFormRef.resetFields()
      this.$refs.editFormRef.clearValidate()
    },
    handleClick () {
      // console.log(this.activeName)
      this.getParams()
    },
    // 级联选择框变化触发函数
    async handleChange () {
      this.getParams()
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      this.catList = res.data
      // console.log(this.catList)
    },
    // 单独封装的获取表单的函数
    async getParams () {
      if (this.selectCatList.length !== 3) {
        this.selectCatList = []
        return false
      }
      // console.log(this.selectCatList)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      // console.log(res.data)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // item.attr_vals = item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTable = res.data
      } else {
        this.onlyTable = res.data
      }
    }
  },
  computed: {
    titletext () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
    isBtnDisabled () {
      if (this.selectCatList.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectCatList.length === 3) {
        // console.log(this.selectCatList)
        return this.selectCatList[2]
      }
      return null
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.cat_opt {
  margin: 15px 0;
}
.input-new-tag {
  width: 100px;
}
.el-tag {
  margin: 0 10px;
}
</style>
